/**
 * 游戏核心逻辑模块
 * 处理拼图游戏的算法和状态管理
 */

// 游戏状态对象
var gameState = {
    size: 3,             // 拼图尺寸 (3,4,5)
    board: [],           // 当前拼图状态
    emptyPos: {x:0, y:0}, // 空白块位置
    moves: 0,            // 移动步数
    time: 0,             // 用时(秒)
    timer: null,         // 计时器引用
    isPlaying: false     // 游戏状态标志
};

// 初始化游戏
function initGame(size) {
    // 验证参数
    if (size < 2 || size > 5) {
        console.error('Invalid puzzle size');
        return;
    }
    
    // 重置游戏状态
    gameState = {
        size: size,
        board: [],
        emptyPos: {x: size-1, y: size-1}, // 空白块初始在右下角
        moves: 0,
        time: 0,
        timer: null,
        isPlaying: false
    };
    
    // 初始化拼图
    initPuzzle();
    
    // 开始游戏
    startGame();
    
    // 渲染拼图板
    renderBoard();
}

// 初始化拼图
function initPuzzle() {
    // 创建有序数组
    var tiles = [];
    for (var i = 1; i < gameState.size * gameState.size; i++) {
        tiles.push(i);
    }
    tiles.push(0); // 0代表空白块
    
    // 随机打乱数组(确保可解)
    do {
        tiles = shuffleArray(tiles);
    } while (!isSolvable(tiles));
    
    // 转换为二维数组
    gameState.board = [];
    for (var i = 0; i < gameState.size; i++) {
        gameState.board[i] = tiles.slice(i * gameState.size, (i + 1) * gameState.size);
    }
    
    // 设置空白块位置
    setEmptyPosition();
}

// Fisher-Yates 洗牌算法
function shuffleArray(array) {
    var newArray = array.slice();
    for (var i = newArray.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = newArray[i];
        newArray[i] = newArray[j];
        newArray[j] = temp;
    }
    return newArray;
}

// 检查拼图是否可解
function isSolvable(tiles) {
    var inversions = 0;
    var size = Math.sqrt(tiles.length);
    
    for (var i = 0; i < tiles.length - 1; i++) {
        for (var j = i + 1; j < tiles.length; j++) {
            if (tiles[i] > tiles[j] && tiles[i] !== 0 && tiles[j] !== 0) {
                inversions++;
            }
        }
    }
    
    // 空白块行从下往上数
    var blankRow = size - Math.floor(tiles.indexOf(0) / size);
    
    if (size % 2 === 1) {
        return inversions % 2 === 0;
    } else {
        return (blankRow % 2 === 1) ? (inversions % 2 === 0) : (inversions % 2 === 1);
    }
}

// 设置空白块位置
function setEmptyPosition() {
    for (var y = 0; y < gameState.size; y++) {
        for (var x = 0; x < gameState.size; x++) {
            if (gameState.board[y][x] === 0) {
                gameState.emptyPos = {x: x, y: y};
                return;
            }
        }
    }
}

// 开始游戏
function startGame() {
    gameState.isPlaying = true;
    gameState.moves = 0;
    gameState.time = 0;
    
    // 启动计时器
    gameState.timer = setInterval(function() {
        gameState.time++;
        updateTimeDisplay();
    }, 1000);
}

// 移动拼图块
function moveTile(x, y) {
    if (!gameState.isPlaying) return;
    
    // 检查是否与空白块相邻
    if ((Math.abs(x - gameState.emptyPos.x) === 1 && y === gameState.emptyPos.y) ||
        (Math.abs(y - gameState.emptyPos.y) === 1 && x === gameState.emptyPos.x)) {
        
        // 交换位置
        gameState.board[gameState.emptyPos.y][gameState.emptyPos.x] = gameState.board[y][x];
        gameState.board[y][x] = 0;
        gameState.emptyPos = {x: x, y: y};
        gameState.moves++;
        
        // 更新UI
        updateMoveCount();
        renderBoard();
        
        // 检查是否完成
        if (checkCompletion()) {
            endGame();
        }
    }
}

// 检查拼图是否完成
function checkCompletion() {
    var expectedValue = 1;
    for (var y = 0; y < gameState.size; y++) {
        for (var x = 0; x < gameState.size; x++) {
            // 跳过最后一个位置(应该是空白块)
            if (y === gameState.size - 1 && x === gameState.size - 1) {
                if (gameState.board[y][x] !== 0) {
                    return false;
                }
            } else {
                if (gameState.board[y][x] !== expectedValue++) {
                    return false;
                }
            }
        }
    }
    return true;
}

// 结束游戏
function endGame() {
    gameState.isPlaying = false;
    clearInterval(gameState.timer);
    
    // 保存分数
    var score = {
        size: gameState.size,
        time: gameState.time,
        moves: gameState.moves,
        date: new Date().toLocaleDateString()
    };
    saveScore(score);
    
    // 显示完成界面
    showGameComplete();
}